package com.project.thisConsume.common.auth;

import com.project.thisCommon.common.redis.RedisConnectionConfig;
import com.project.thisConsume.common.redis.auth.AuthConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AnonymousConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Autowired
    AuthConfig authConfig;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
                .tokenServices(tokenServices())
                //资源ID
                .resourceId(authConfig.getResource());

        super.configure(resources);

//        resources.resourceId(authConfig.getResource()).stateless(true);
    }

    @Bean
    public TokenStore tokenStore() {
        RedisTokenStore redis = new RedisTokenStore(RedisConnectionConfig.createLettuceConnectionFactory(
                authConfig.getRedis().getDatabase(),
                authConfig.getRedis().getHost(),
                authConfig.getRedis().getPort(),
                authConfig.getRedis().getPassword(),
                authConfig.getRedis().getLettuce().getMaxIdle(),
                authConfig.getRedis().getLettuce().getMinIdle(),
                authConfig.getRedis().getLettuce().getMaxActive(),
                authConfig.getRedis().getLettuce().getMaxWait(),
                authConfig.getRedis().getTimeout(),
                authConfig.getRedis().getShutdownTimeOut()));

        return redis;
    }

    @Bean
    public DefaultTokenServices tokenServices(){
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        return defaultTokenServices;
    }
    /**
     * @Description 加密方式
     * @Date 2019/7/15 18:06
     * @Version  1.0
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        HttpSecurity auth = http
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                .requestMatchers().anyRequest()
                .and()
                .anonymous().and();

        for(String s : authConfig.getPrefixs()){
            auth = auth
                    .authorizeRequests()
                    .antMatchers(String.format("/%s/**", s))
                    .authenticated()
                    .and();
        }
//                .and()
//                .authorizeRequests()
////                    .antMatchers("/product/**").access("#oauth2.hasScope('select') and hasRole('ROLE_USER')")
//                .antMatchers(String.format("/%s/**", prefix)).authenticated();//配置resource访问控制，必须认证过后才可以访问
    }
}
